package com.foreverwin.mes.lims.service.impl;

import com.foreverwin.mes.common.enums.IDUtils;
import com.foreverwin.mes.core.base.FrontPage;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.lims.mapper.InactiveTimeMapper;
import com.foreverwin.mes.lims.mapper.ItemTankMapper;
import com.foreverwin.mes.lims.model.InactiveTime;
import com.foreverwin.mes.lims.model.ItemTank;
import com.foreverwin.mes.lims.model.LotTank;
import com.foreverwin.mes.lims.mapper.LotTankMapper;
import com.foreverwin.mes.lims.service.LotTankService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
 * <p>
 * 物料批次出入罐 服务实现类
 * </p>
 *
 * @author Max
 * @since 2020-03-11
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LotTankServiceImpl extends ServiceImpl<LotTankMapper, LotTank> implements LotTankService {

    private static Logger logger = LoggerFactory.getLogger( LotTankServiceImpl.class);

    @Autowired
    private LotTankMapper lotTankMapper;
    @Autowired
    private InactiveTimeMapper inactiveTimeMapper;
    @Autowired
    private ItemTankMapper itemTankMapper;

    @Override
    public Page<LotTank> selectPage(FrontPage<LotTank> frontPage, LotTank lotTank) {
        EntityWrapper<LotTank> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(lotTank);
        return super.selectPage(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<LotTank> selectList(LotTank lotTank) {
        EntityWrapper<LotTank> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(lotTank);
        return super.selectList(queryWrapper);
    }

    /**
     * 批次出入罐处理
     *
     * @param site
     * @param tank
     * @param lot
     * @param item
     * @param moveType
     * @param actionTime
     */
    @Override
    public void lotCheckinOrCheckOut(String site, String tank, String lot, String qty,String item, String moveType, Date actionTime) {

        //查询批次的罐子是否有维护时间上下限设置
        InactiveTime inactiveTime = new InactiveTime();
        inactiveTime.setSite( site );
        inactiveTime.setResrce( tank );
        inactiveTime.setItem( item );
        InactiveTime itime = inactiveTimeMapper.selectOne( inactiveTime );
        if ( itime == null ) {

            logger.error("罐子["+tank+"]未维护呆滞时间设置");
            return;
        }
        String zInactiveTimeBo = itime.getHandle();
        //查询当前是否有正在执行养豆或者养粉的罐子
        ItemTank itemTank = new ItemTank();
        itemTank.setzInactiveTimeBo( zInactiveTimeBo );
        ItemTank iTank = itemTankMapper.selectCurrentTank( itemTank );

        if ( iTank == null ) {
            //熟豆罐
            if ( "1".equals( itime.getTankByUse() )) {
                iTank = new  ItemTank();
                iTank.setHandle(IDUtils.createID());
                iTank.setzInactiveTimeBo( zInactiveTimeBo );
                iTank.setShortCode( itime.getShortCode() );
                iTank.setResrce( itime.getResrce() );
                iTank.setResrceDesc( itime.getResrceDesc() );
                iTank.setUpperLimit( itime.getUpperLimit() );
                iTank.setLowerLimit( itime.getLowerLimit() );
                iTank.setTankByUse( itime.getTankByUse() );
                iTank.setTankStatus("1");
                iTank.setStatus( "0" );
                iTank.setStartTime( actionTime );
                if ( actionTime != null ) {
                    iTank.setEstimateLowerTime( new Date( actionTime.getTime() + itime.getLowerLimit()* 60*60*1000));
                    iTank.setEstimateUpperTime( new Date( actionTime.getTime() + itime.getUpperLimit()* 60*60*1000 ));
                }
                iTank.setInactiveTime( new BigDecimal(0) );
                iTank.setTotalDelayTime( new BigDecimal(0) );
                iTank.setReleaseNum( 0 );
                iTank.setModifiedDateTime( new Date() );
                iTank.setCreatedDateTime( new Date() );
                itemTankMapper.insert( iTank );

                //绑定当前批次
                LotTank lotTank = new LotTank();
                lotTank.setHandle( IDUtils.createID() );
                lotTank.setzItemTankBo( iTank.getHandle() );
                lotTank.setLot( lot );
                lotTank.setSite( site );
                lotTank.setResrce( tank );
                lotTank.setItem( itime.getItem() );
                lotTank.setItemDesc( itime.getItemDesc() );
                lotTank.setLotStatus("0");
                lotTank.setCheckinQty( qty );
                lotTank.setCheckinTime( actionTime );
                lotTank.setMoveType( moveType );
                lotTank.setCreatedDateTime( new Date() );
                lotTank.setModifiedDateTime( new Date() );
                lotTankMapper.insert(lotTank);
            } else if ( "2".equals( itime.getTankByUse() ) ) {
                iTank = new  ItemTank();
                iTank.setHandle(IDUtils.createID());
                iTank.setzInactiveTimeBo( zInactiveTimeBo );
                iTank.setShortCode( itime.getShortCode() );
                iTank.setResrce( itime.getResrce() );
                iTank.setResrceDesc( itime.getResrceDesc() );
                iTank.setUpperLimit( itime.getUpperLimit() );
                iTank.setLowerLimit( itime.getLowerLimit() );
                iTank.setTankByUse( itime.getTankByUse() );
                iTank.setStatus( "0" );
                iTank.setTankStatus("1");
                if ( actionTime != null ) {
                    iTank.setEstimateLowerTime( new Date( actionTime.getTime() + itime.getLowerLimit()* 60*60*1000));
                    iTank.setEstimateUpperTime( new Date( actionTime.getTime() + itime.getUpperLimit()* 60*60*1000 ));
                }
                iTank.setInactiveTime( new BigDecimal(0 ) );
                iTank.setTotalDelayTime( new BigDecimal(0) );
                iTank.setReleaseNum( 0 );
                iTank.setModifiedDateTime( new Date() );
                iTank.setCreatedDateTime( new Date() );
                itemTankMapper.insert( iTank );

                //绑定当前批次
                LotTank lotTank = new LotTank();
                lotTank.setHandle( IDUtils.createID() );
                lotTank.setzItemTankBo( iTank.getHandle() );
                lotTank.setLot( lot );
                lotTank.setSite( site );
                lotTank.setResrce( tank );
                lotTank.setItem( itime.getItem() );
                lotTank.setItemDesc( itime.getItemDesc() );
                lotTank.setLotStatus("0");
                lotTank.setCheckinQty( qty );
                lotTank.setCheckinTime( actionTime );
                lotTank.setMoveType( moveType );
                lotTank.setCreatedDateTime( new Date() );
                lotTank.setModifiedDateTime( new Date() );
                lotTankMapper.insert(lotTank);
            } else {
                logger.error("罐子["+tank+"]用途编号有误");
                return;
            }

        } else {
            /**
             * 进罐
             */
            if ("1".equals( moveType ) ) {
                /**
                 * 熟豆罐
                 */
                if ( "1".equals(itime.getTankByUse()) ) {
                    //检查罐子是否有开始时间
                    if ( iTank.getStartTime() == null) {
                        iTank.setStartTime( actionTime );
                    }

                    LotTank lotTank = new LotTank();
                    lotTank.setHandle( IDUtils.createID() );
                    lotTank.setzItemTankBo( iTank.getHandle() );
                    lotTank.setLot( lot );
                    lotTank.setSite( site );
                    lotTank.setResrce( tank );
                    lotTank.setItem( itime.getItem() );
                    lotTank.setItemDesc( itime.getItemDesc() );
                    lotTank.setLotStatus("0");
                    lotTank.setCheckinQty( qty );
                    lotTank.setCheckinTime( actionTime );
                    lotTank.setMoveType( moveType );
                    lotTank.setCreatedDateTime( new Date() );
                    lotTank.setModifiedDateTime( new Date() );
                    lotTankMapper.insert(lotTank);

                } else if ( "2".equals(itime.getTankByUse()) ) {
                /**
                 * 粉罐
                 */
                    //绑定当前批次
                    LotTank lotTank = new LotTank();
                    lotTank.setHandle( IDUtils.createID() );
                    lotTank.setzItemTankBo( iTank.getHandle() );
                    lotTank.setLot( lot );
                    lotTank.setSite( site );
                    lotTank.setResrce( tank );
                    lotTank.setItem( itime.getItem() );
                    lotTank.setItemDesc( itime.getItemDesc() );
                    lotTank.setMoveType("1");
                    lotTank.setLotStatus("0");
                    lotTank.setCheckinQty( qty );
                    lotTank.setCheckinTime( actionTime );
                    lotTank.setMoveType( moveType );
                    lotTank.setCreatedDateTime( new Date() );
                    lotTank.setModifiedDateTime( new Date() );
                    lotTankMapper.insert(lotTank);
                } else {
                    logger.error("罐子["+tank+"]入罐时，罐子的用途类型有误");
                    return;
                }
            } else if ("2".equals( moveType )) {
            /**
             * 出罐
             */
                if ( "1".equals(itime.getTankByUse()) ) {
                    //查询该批次的进入记录
                    LotTank lotTank = new LotTank();
                    lotTank.setLot( lot );
                    LotTank _lotTank =lotTankMapper.selectOne( lotTank );
                    if ( _lotTank == null ) {
                        logger.error("无法查询到批次["+lot+"]入罐信息，该批次出罐失败");
                        return;
                    }
                    _lotTank.setCheckoutTime( actionTime );
                    _lotTank.setMoveType( moveType );
                    _lotTank.setModifiedDateTime( new Date());
                    lotTankMapper.updateById( _lotTank );

                    //更新罐子的开始计时时间
                    List<LotTank> lotTankList = selectLotInTank( iTank.getHandle() );
                    Date startTime = null;
                    for (LotTank lt : lotTankList) {
                        startTime = lt.getCheckinTime();
                        break;
                    }
                    if ( startTime != null ) {
                        iTank.setStartTime(startTime);
                    }
                    itemTankMapper.updateById( iTank );
                } else if ( "2".equals(itime.getTankByUse()) ) {
                    /**
                     * 粉罐
                     */
                    //查询该批次的进入记录
                    LotTank lotTank = new LotTank();
                    lotTank.setLot( lot );
                    LotTank _lotTank =lotTankMapper.selectOne( lotTank );
                    if ( _lotTank == null ) {
                        logger.error("无法查询到批次["+lot+"]入罐信息，该批次出罐失败");
                        return;
                    }
                    _lotTank.setCheckoutTime( actionTime );
                    _lotTank.setMoveType( moveType );
                    _lotTank.setModifiedDateTime( new Date());
                    lotTankMapper.updateById( _lotTank );
                } else {
                    logger.error("罐子["+tank+"]出罐时，罐子的用途类型有误");
                    return;
                }
            } else {
                logger.error("罐子["+tank+"]进出罐类型有误");
                return;
            }
        }
    }

    /**
     * 通过外键查询罐内批次入罐时间升序
     *
     * @param zItemTankBo
     * @return
     */
    @Override
    public List<LotTank> selectLotInTank(String zItemTankBo) {
        return lotTankMapper.selectLotInTank(zItemTankBo);
    }

    @Override
    public List<LotTank> selectLotOfTankList(String zItemTankBo) {
        return lotTankMapper.selectLotOfTankList( zItemTankBo );
    }


}